package com.fangcang.ebk.finance.bill.controller;

import com.fangcang.common.PaginationSupportDTO;
import com.fangcang.common.ResponseDTO;
import com.fangcang.common.enums.BalanceMethodEnum;
import com.fangcang.common.enums.ErrorCodeEnum;
import com.fangcang.common.enums.ResultCodeEnum;
import com.fangcang.common.util.ExcelHelper;
import com.fangcang.common.util.ReportTemplateConfig;
import com.fangcang.ebk.common.controller.BaseController;
import com.fangcang.finance.bill.request.BillIdDTO;
import com.fangcang.finance.bill.request.QueryBillDTO;
import com.fangcang.finance.bill.response.BillDTO;
import com.fangcang.finance.bill.response.BillOrderItemExportDTO;
import com.fangcang.finance.bill.service.SupplyBillService;
import com.fangcang.merchant.dto.MerchantDTO;
import com.fangcang.merchant.request.QueryMerchantDTO;
import com.fangcang.merchant.response.UserBankCardResponseDTO;
import com.fangcang.merchant.service.MerchantService;
import com.fangcang.merchant.service.UserService;
import com.fangcang.supplier.request.SingleUserRequestDTO;
import com.fangcang.supplier.response.SingleSupplyInfoResponseDTO;
import com.fangcang.supplier.service.SupplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping(("/ebk/finance/bill"))
public class SupplierBillController extends BaseController {

    @Autowired
    private SupplyBillService supplyBillService;

    @Autowired
    private SupplyService supplyService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private UserService userService;

    @Autowired
    private ReportTemplateConfig reportTemplateConfig;

    /**
     * 查询供应商账单
     */
    @RequestMapping(value = "/querySupplierBill", method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ResponseDTO querySupplierBill(@RequestBody QueryBillDTO requestDTO) {
        log.info("querySupplierBill param:"+requestDTO);
        ResponseDTO responseDTO=null;
        try{
            requestDTO.setOrgCode(super.getCacheUser().getSupplyCode());
            requestDTO.setMerchantCode(super.getCacheUser().getMerchantCode());
            PaginationSupportDTO paginationSupportDTO=supplyBillService.querySupplyBill(requestDTO);
            responseDTO=new ResponseDTO(ResultCodeEnum.SUCCESS.code);
            responseDTO.setModel(paginationSupportDTO);
        }catch (Exception e){
            log.error("supplyBillService.querySupplyBill 异常",e);
            responseDTO=new ResponseDTO(ResultCodeEnum.FAILURE.code,null, ErrorCodeEnum.SYSTEM_EXCEPTION.errorDesc);
        }
        return responseDTO;
    }

    /**
     * 导出账单
     */
    @RequestMapping(value = "/exportSupplierBill")
    public void exportSupplierBill(BillIdDTO requestDTO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("exportSupplierBill param:"+requestDTO);
        QueryBillDTO queryBillDTO=new QueryBillDTO();
        queryBillDTO.setBillId(requestDTO.getBillId());
        queryBillDTO.setMerchantCode(super.getCacheUser().getMerchantCode());
        PaginationSupportDTO<BillDTO> billPaginationSupportDTO=supplyBillService.querySupplyBill(queryBillDTO);
        BillDTO billDTO=billPaginationSupportDTO.getItemList().get(0);
        List<BillOrderItemExportDTO> billOrderItemExportDTOList=supplyBillService.exportBillOrderItem(requestDTO);

        SingleUserRequestDTO singleUserRequestDTO=new SingleUserRequestDTO();
        singleUserRequestDTO.setSupplyCode(billDTO.getOrgCode());
        ResponseDTO<SingleSupplyInfoResponseDTO> supplyInfoResponseDTO=supplyService.getSupplyById(singleUserRequestDTO);

        QueryMerchantDTO queryMerchantDTO=new QueryMerchantDTO();
        queryMerchantDTO.setMerchantCode(super.getCacheUser().getMerchantCode());
        MerchantDTO merchantDTO=merchantService.queryMerchant(queryMerchantDTO);

        ResponseDTO<UserBankCardResponseDTO> userBankCardResponseDTO=userService.queryUserBankCardList(merchantDTO.getMerchantId());

        Map data = new HashMap();
        data.put("bill", billDTO);
        data.put("billItemList", billOrderItemExportDTOList);
        data.put("merchant", merchantDTO);
        data.put("bankCardList",userBankCardResponseDTO.getModel().getBankCardList());
        data.put("agent",supplyInfoResponseDTO.getModel());
        data.put("balanceMethod", BalanceMethodEnum.getValueByKey(supplyInfoResponseDTO.getModel().getBillingMethod()));
        data.put("sender",super.getCacheUser().getRealName());

        OutputStream output = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            ByteArrayInputStream byteArrayInputStream = ExcelHelper.exportFromRemote(data, reportTemplateConfig.getAgentBillReportUrl());
            //告诉浏览器用什么软件可以打开此文件
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            // 下载文件的默认名称
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("供应商账单.xls","UTF-8"));

            output = response.getOutputStream();
            bis = new BufferedInputStream(byteArrayInputStream);
            bos = new BufferedOutputStream(output);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            log.error("exportAgentBill has error",e);
        }finally {
            if (null != bos) {
                bos.close();
            }
            if (null != bis) {
                bis.close();
            }
            if (null != output) {
                output.close();
            }
        }
    }
}
